<template>
  <div class="page">
    <Form inline>
      <FormItem>
        <Button type="info" @click="Export">导出</Button>
      </FormItem>
    </Form>
    <Table border ref="tableGrid" :columns="columns2" :data="dataGrid" :span-method="handleSpan"></Table>
  </div>
</template>
<script>
import { saveAs } from 'file-saver'
import * as XLSX from 'xlsx'
export default {
  name: 'OrderExport',
  data() {
    return {
      dataGrid: [],
      columns2: [
        {
          title: '日期',
          key: 'postTime',
          sortable: true,
          width: 110,
        },
        {
          title: '收货人',
          key: 'consigneeName',
          width: 100,
        },
        {
          title: '客户电话',
          key: 'consigneeMobile',
          width: 125,
        },
        {
          title: '网点',
          key: 'srvGroupName',
          width: 150,
        },
        {
          title: '收货地址',
          key: 'addressDetail',
          minWidth: 180,
        },
        {
          title: '订单号',
          key: 'shopOrderId',
          width: 200,
        },
        {
          title: '订单状态',
          key: 'orderStatusTips',
          width: 110,
          render: (h, params) => {
            return h('div', [
              h(
                'Tag',
                {
                  props: {
                    color: this.$dict.orderStatus.color(params.row.orderStatus),
                  },
                },
                params.row.orderStatusTips
              ),
            ])
          },
        },
        {
          title: '订单数量',
          key: 'goodsTotalQty',
          width: 100,
        },
        {
          title: '订单总金额',
          key: 'settleAmt',
          width: 120,
        },
        {
          title: '商品名称',
          key: 'goodsName',
          minWidth: 200,
        },
        {
          title: '数量',
          key: 'goodsQty',
          width: 80,
        },
        {
          title: '单价',
          key: 'salePrice',
          width: 80,
        },
        {
          title: '单位',
          key: 'skuUom',
          width: 80,
        },
        {
          title: '小计金额',
          key: 'actualAmt',
          width: 110,
        },
      ],
    }
  },
  props: {
    fileName: String,
  },
  created() {},
  components: {},
  methods: {
    //获取仓库门店订单，调用方包括供应商和前置仓库
    init(query) {
      query.pageSize = 5000
      query.orderBy = {
        asc: true,
        fields: ['shop_order_id'],
      }
      new this.$rest({
        gateway: 'agrobiz',
        service: 'agrobiz-order',
        url: '/v1.0/view/mall/order/detail/page',
        query: query,
        action: (res) => {
          if (res.data.code === 20000) {
            this.dataGrid = res.data.data.list
            this.dataGrid.forEach((element) => {
              element.orderStatusTips = this.$dict.orderStatus.name(element.orderStatus)
              element.postTime = this.$date(element.postTime, 'yyyy-MM-dd')
              element.srvGroupName = element.srvGroupName ? element.srvGroupName : '--'
            })
          } else {
            this.$Notice.warning({
              title: '获取失败',
              desc: `失败原因：${res.data.msg}`,
            })
          }
        },
      }).get()
    },
    handleSpan({ row, column, rowIndex, columnIndex }) {
      //iview table 将前8列根据shopOrderId值相同的行合并成1行，实现订单主表与明细表的合并
      if (columnIndex < 9) {
        //从this.dataGrid中统计同一个shopOrderId的行数
        const sameRows = this.dataGrid.filter((item) => item.shopOrderId === row.shopOrderId)
        const preRow = this.dataGrid[rowIndex - 1]
        const nextRow = this.dataGrid[rowIndex + 1]
        if (preRow && row.shopOrderId === preRow.shopOrderId) {
          return [0, 0]
        } else if (nextRow && row.shopOrderId === nextRow.shopOrderId) {
          return [sameRows.length, 1]
        }
      }
    },
    Export() {
      const filename = `${this.fileName}_${this.$date(new Date(), 'yyyy-MM-dd-HH-mm')}`
      // this.$refs.tableGrid.exportCsv({
      //   filename: `${this.$store.getOrg('orgName')}_${this.$date(new Date(), 'yyyy_MM_dd')}_${new Date().getTime()}`,
      //   original: false,
      // })
      const excelGrid = []
      this.dataGrid.forEach((element) => {
        let item = {}
        item.postTime = element.postTime
        item.consigneeName = element.consigneeName
        item.consigneeMobile = element.consigneeMobile
        item.addressDetail = element.addressDetail
        item.shopOrderId = element.shopOrderId
        item.orderStatusTips = element.orderStatusTips
        item.goodsTotalQty = element.goodsTotalQty
        item.settleAmt = element.settleAmt
        item.goodsName = element.goodsName
        item.goodsQty = element.goodsQty
        item.salePrice = element.salePrice
        item.skuUom = element.skuUom
        item.actualAmt = element.actualAmt
        excelGrid.push(item)
      })
      this.exportExcelWithMerge(excelGrid,filename)
    },
    // 带合并功能的导出
    exportExcelWithMerge(data, fileName = '导出数据') {
      // 1. 按shopOrderId分组
      const groupedData = this.groupByShopOrderId(data)
      // 2. 创建工作簿
      const wb = XLSX.utils.book_new()

      // 3. 处理数据并生成合并信息
      const { sheetData, merges } = this.processDataForMerge(groupedData)
      // 4. 创建工作表
      const ws = XLSX.utils.json_to_sheet(sheetData)

      // 5. 设置合并区域
      if (merges.length > 0) {
        ws['!merges'] = merges
      }

      // 6. 添加到工作簿并导出
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
      const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
      saveAs(new Blob([wbout], { type: 'application/octet-stream' }), `${fileName}.xlsx`)
    },
    // 按shopOrderId分组
    groupByShopOrderId(data) {
      const groups = {}
      data.forEach((item) => {
        if (!groups[item.shopOrderId]) {
          groups[item.shopOrderId] = []
        }
        groups[item.shopOrderId].push(item)
      })
      return groups
    },
    // 处理数据生成合并信息
    processDataForMerge(groupedData) {
      const sheetData = []
      const merges = []
      let currentRow = 1

      // Create mapping from field keys to Chinese titles
      const fieldTitleMap = {}
      this.columns2.forEach((column) => {
        fieldTitleMap[column.key] = column.title
      })

      Object.keys(groupedData).forEach((shopOrderId) => {
        const group = groupedData[shopOrderId]
        const groupSize = group.length

        // Process first row - convert field names to Chinese headers
        if (group.length > 0) {
          const firstRow = group[0]
          const processedFirstRow = {}

          // Map all fields to their Chinese titles
          Object.keys(firstRow).forEach((key) => {
            const title = fieldTitleMap[key] || key
            processedFirstRow[title] = firstRow[key]
          })

          sheetData.push(processedFirstRow)
        }

        // Process remaining rows - convert field names to Chinese headers
        for (let i = 1; i < groupSize; i++) {
          const rowData = group[i]
          const processedRowData = {}

          // Map fields to Chinese titles and clear first 8 fields for merging
          Object.keys(rowData).forEach((key, index) => {
            const title = fieldTitleMap[key] || key
            // Clear first 8 fields for merging
            if (index < 8) {
              processedRowData[title] = ''
            } else {
              processedRowData[title] = rowData[key]
            }
          })

          sheetData.push(processedRowData)
        }

        // 生成合并区域（前8列合并）
        if (groupSize > 1) {
          for (let col = 0; col < 8; col++) {
            merges.push({
              s: { r: currentRow, c: col }, // 起始位置
              e: { r: currentRow + groupSize - 1, c: col }, // 结束位置
            })
          }
        }

        currentRow = currentRow + groupSize
      })

      return { sheetData, merges }
    },
  },
}
</script>
